﻿using Nancy;
using Nancy.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace customer.dao.V2
{
    public class QueryModel
    {   
        public string sql { get; set; }

        public int pageindex { get; set; }
        public int pagesize { get; set; }

        public string pk { get; set; }
    }


    public class QueryModelBinder : IModelBinder
    {

        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var queryModel = (instance as QueryModel) ?? new QueryModel();

            System.IO.Stream s = context.Request.Body;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            
            string json = builder.ToString();

            queryModel = Newtonsoft.Json.JsonConvert.DeserializeObject<QueryModel>(json);
            return queryModel;
        }

        public bool CanBind(Type modelType)
        {   
            return modelType == typeof(QueryModel);
        }
    }
}
